import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { NFCTag } from '@/types';
import { Platform } from 'react-native';

interface NFCState {
  tags: NFCTag[];
  isScanning: boolean;
  error: string | null;
  
  // NFC operations
  startScan: () => void;
  stopScan: () => void;
  writeTag: (contentId: string) => Promise<boolean>;
  readTag: () => Promise<string | null>; // Returns contentId if found
  
  // Tag management
  addTag: (tag: NFCTag) => void;
  removeTag: (tagId: string) => void;
  getContentIdFromTag: (tagId: string) => string | null;
}

// Create a fallback storage for web environments where AsyncStorage might not be available
const createNoopStorage = () => {
  return {
    getItem: (_name: string) => Promise.resolve(null),
    setItem: (_name: string, _value: string) => Promise.resolve(),
    removeItem: (_name: string) => Promise.resolve(),
  };
};

// Use AsyncStorage when available, otherwise use a noop storage
const storage = Platform.OS === 'web' 
  ? createNoopStorage()
  : AsyncStorage;

export const useNFCStore = create<NFCState>()(
  persist(
    (set, get) => ({
      tags: [],
      isScanning: false,
      error: null,
      
      startScan: () => {
        // In a real app, we would use a library like react-native-nfc-manager
        // to start scanning for NFC tags
        set({ isScanning: true, error: null });
      },
      
      stopScan: () => {
        set({ isScanning: false });
      },
      
      writeTag: async (contentId: string) => {
        try {
          // Simulate writing to an NFC tag
          await new Promise(resolve => setTimeout(resolve, 1500));
          
          // Generate a random tag ID
          const tagId = Math.random().toString(36).substring(2, 15);
          
          // Create a new tag
          const newTag: NFCTag = {
            id: tagId,
            contentId,
            lastScanned: new Date().toISOString(),
          };
          
          // Add the tag to the store
          get().addTag(newTag);
          
          return true;
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : 'Failed to write to NFC tag',
            isScanning: false 
          });
          return false;
        }
      },
      
      readTag: async () => {
        try {
          set({ isScanning: true, error: null });
          
          // Simulate reading from an NFC tag
          await new Promise(resolve => setTimeout(resolve, 1500));
          
          // For demo purposes, return a random tag from the store
          const { tags } = get();
          
          if (tags.length === 0) {
            set({ 
              error: 'No NFC tags found. Please write to a tag first.',
              isScanning: false 
            });
            return null;
          }
          
          const randomTag = tags[Math.floor(Math.random() * tags.length)];
          
          // Update the last scanned time
          const updatedTags = tags.map(tag => 
            tag.id === randomTag.id 
              ? { ...tag, lastScanned: new Date().toISOString() } 
              : tag
          );
          
          set({ tags: updatedTags, isScanning: false });
          
          return randomTag.contentId;
        } catch (error) {
          set({ 
            error: error instanceof Error ? error.message : 'Failed to read NFC tag',
            isScanning: false 
          });
          return null;
        }
      },
      
      addTag: (tag: NFCTag) => {
        const { tags } = get();
        set({ tags: [...tags, tag], isScanning: false });
      },
      
      removeTag: (tagId: string) => {
        const { tags } = get();
        set({ tags: tags.filter(tag => tag.id !== tagId) });
      },
      
      getContentIdFromTag: (tagId: string) => {
        const { tags } = get();
        const tag = tags.find(tag => tag.id === tagId);
        return tag ? tag.contentId : null;
      },
    }),
    {
      name: 'nfc-storage',
      storage: createJSONStorage(() => storage),
    }
  )
);